﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Dapper;
using log4net;
using Quartz;
using QuartzTopshelf.Model;

namespace QuartzTopshelf.Jobs
{
    public sealed class TestJob : IJob
    {
        private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private static string connStr = ConfigurationManager.AppSettings["connectionstring"];
        private static string connectionstringTarget = ConfigurationManager.AppSettings["connectionstringTarget"];

        private static bool isBusy = false;
        /// <summary>
        /// Called by the <see cref="IScheduler" /> when a <see cref="ITrigger" />
        /// fires that is associated with the <see cref="IJob" />.
        /// </summary>
        /// <remarks>
        /// The implementation may wish to set a  result object on the 
        /// JobExecutionContext before this method exits.  The result itself
        /// is meaningless to Quartz, but may be informative to 
        /// <see cref="IJobListener" />s or 
        /// <see cref="ITriggerListener" />s that are watching the job's 
        /// execution.
        /// </remarks>
        /// <param name="context">The execution context.</param>
        public async Task Execute(IJobExecutionContext context)
        {
            ////通过配置文件传递参数
            //JobDataMap dataMap = context.JobDetail.JobDataMap;
            //string key3 = dataMap.GetString("key3");
            //logger.Info("key3 : " + key3);
            //string key4 = dataMap.GetString("key4");
            //logger.Info("key4 : " + key4);

            //logger.Info("TestJob running...");
            ////Thread.Sleep(TimeSpan.FromSeconds(5));
            //await Console.Out.WriteLineAsync("TestJob is executing.");
            //logger.Info("TestJob run finished.");
            if (!isBusy)
            {
                try
                {
                    isBusy = true;
                    var maxId = 0;
                    IList<test> testList = null;
                    using (var conn = new SqlConnection(connectionstringTarget))
                    {
                        conn.Open(); // 打开数据库连接
                        var query = @"SELECT max([order]) FROM test"; // SQL查询语句
                        maxId = conn.ExecuteScalar<int>(query); // 执行查询操作并将结果存储在result变量中
                    }

                    using (var conn = new SqlConnection(connStr))
                    {
                        conn.Open(); // 打开数据库连接
                        // 一次处理50条数据
                        var query = $"SELECT top 50 * FROM test where [order]>{maxId} order by [order]"; // SQL查询语句
                        testList = conn.Query<test>(query).ToList(); // 执行查询操作并将结果存储在result变量中
                    }

                    if (testList.Any())
                    {
                        using (var conn2 = new SqlConnection(connectionstringTarget))
                        {
                            conn2.Open(); // 打开数据库连接

                            foreach (var test in testList)
                            {
                                var query = $"SELECT * FROM test where id='{test.id}'"; // SQL查询语句
                                var item = conn2.QueryFirstOrDefault<test>(query);
                                if (item != null)
                                {
                                    var sql = $"update test set id='{test.id}', [order]={test.order} where id='{test.id}'";
                                    conn2.Execute(sql);
                                }
                                else
                                {
                                    var sql = $"insert into test(id,[order]) values('{test.id}', {test.order})";
                                    conn2.Execute(sql);
                                }
                            }
                        }
         
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex);
                }
                finally
                {
                    isBusy = false;
                }
            }
        }
    }
}
